﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Caching.Distributed;
using TomNet.AspNetCore.Mvc;
using TomNet.SqlSugarCore.Entity;
using Microsoft.Extensions.DependencyInjection;
using TomNet.AspNetCore.Data;
using TomNet.Data;
using TomNet.App.Model.DB;
using TomNet.App.Core.Contracts;
using TomNet.Security.Claims;

namespace TomNet.App.Web.Controllers.API
{
	[Common.ApiAuthentication]
	public partial class PageController : Common.APIController
	{
		private readonly IUnitOfWork _unitOfWork;
		private IDistributedCache _cache;
		//private IHttpClientFactory _httpClientFactory;
		private readonly IBusinessContract _businessContract;
        private readonly ICoinContract _coinContract;
        private readonly IBusinessIncomeRunningsContract _businessIncomeRunningsContract;        
        private readonly Core.Contracts.Identity.IUsersContract _usersContract;

		public PageController(
			IUnitOfWork unitOfWork,
			IServiceProvider provider,
			IBusinessContract businessContract,
            ICoinContract coinContract,
            IBusinessIncomeRunningsContract businessIncomeRunningsContract,            
            Core.Contracts.Identity.IUsersContract usersContract)
		{
			_unitOfWork = unitOfWork;
			_cache = provider.GetService<IDistributedCache>();
			//_httpClientFactory = httpClientFactory;
			_businessContract = businessContract;
            _coinContract = coinContract;
            _businessIncomeRunningsContract = businessIncomeRunningsContract;            
            _usersContract = usersContract;
		}

		#region Service.Model.PoolCoinDetails BTCPoolDetails BTC币种信息。

		/// <summary>
		/// BTC币种信息。
		/// </summary>
		public Service.Model.PoolCoinDetails BTCPoolDetails
		{
			get
			{
				Service.Model.PoolCoinDetails model = Service.FkPool.PoolCoinDetails();
				if (model != null)
					_btcpooldetails = model;

				if (_btcpooldetails == null)
				{
					_btcpooldetails = new Service.Model.PoolCoinDetails
					{
						Throughput = 0.00001617m,
						ThroughputUnit = "T",
						Price = 9573m,
						PriceTrend = -5.15272m,
						Exchange = 6.998297m
					};
				}

				return _btcpooldetails;
			}
		}

		private static Service.Model.PoolCoinDetails _btcpooldetails = null;

		#endregion


		#region AjaxResult HeyueSaixuan(HeyueSaixuanParameter parameter)

		public AjaxResult HeyueSaixuan(HeyueSaixuanParameter parameter)
		{
			//订单列表
			var query = _businessContract.UnitOfWork.DbContext.Queryable<Model.DB.Business, Model.DB.Identity.Users>(
				(a, b) => a.UserId == b.Id)
				.Where((a, b) => a.UserId == LoginUserId)
				.OrderBy((a, b) => a.CreatedTime)
				.Select((a, b) => new HeyueSaixuanRowsModel
				{
					Id = a.Id,
					ProductName = a.ProductName,
					Hashrate = a.Hashrate,
					HashrateString = a.Hashrate.ToString(),
					Number = a.Number,
					State = a.State.ToString()
				});

			//分页及数据处理
			int total = 0;
			var list = query.ToPageList(parameter.Page, parameter.Limit, ref total);

			foreach (var entity in list)
			{
				entity.HashrateString = entity.Hashrate.ConvertHashrate(space: " ");
				entity.State = Common.Utility.BusinessStateString(Convert.ToInt32(entity.State));
			}

			//返回数据
			var result = new HeyueSaixuanModel
			{
				Rows = list,
				Total = total
			};

			return new AjaxResult("Success", AjaxResultType.Success, result);
		}

		public class HeyueSaixuanParameter
		{
			public int Page { get; set; } = 1;
			public int Limit { get; set; } = 20;
		}

		public class HeyueSaixuanModel
		{
			public List<HeyueSaixuanRowsModel> Rows { get; set; } = new List<HeyueSaixuanRowsModel>();
			public int Total { get; set; }
		}

		public class HeyueSaixuanRowsModel
		{
			public int Id { get; set; }
			public string ProductName { get; set; }
			public decimal Hashrate { get; set; }
			public string HashrateString { get; set; }
			public int Number { get; set; }
			public string State { get; set; }
		}

		#endregion

		#region AjaxResult HeyueGuanli(HeyueGuanliParameter parameter)

		[HttpPost]
		public AjaxResult HeyueGuanli(HeyueGuanliParameter parameter)
		{
			//订单列表
			var query = _businessContract.UnitOfWork.DbContext.Queryable<Model.DB.Business, Model.DB.Identity.Users>(
			   (a, b) => a.UserId == b.Id)
			   .Where((a, b) => a.UserId == LoginUserId)
			   .OrderBy((a, b) => a.CreatedTime)
			   .Select((a, b) => new HeyueGuanliRowsModel
			   {
				   Id = a.Id,
				   ProductName = a.ProductName,
				   Hashrate = a.Hashrate,
				   HashrateString = a.Hashrate.ToString(),
				   Price = a.Price,
				   Number = a.Number,
				   Amount = a.Amount,
				   CreatedTime = a.CreatedTime
			   });

			//分页及数据处理
			int total = 0;
			var list = query.ToPageList(parameter.Page, parameter.Limit, ref total);

			foreach (var entity in list)
			{
				entity.HashrateString = entity.Hashrate.ConvertHashrate(space: " ");
			}

			//返回数据
			var result = new HeyueGuanliModel
			{
				Rows = list,
				Total = total
			};

			return new AjaxResult("Success", AjaxResultType.Success, result);
		}

		public class HeyueGuanliParameter
		{
			public int Page { get; set; } = 1;
			public int Limit { get; set; } = 20;
		}

		public class HeyueGuanliModel
		{
			public List<HeyueGuanliRowsModel> Rows { get; set; }
			public int Total { get; set; }
		}

		public class HeyueGuanliRowsModel
		{
			public int Id { get; set; }
			public string ProductName { get; set; }
			public decimal Hashrate { get; set; }
			public string HashrateString { get; set; }
			public decimal Price { get; set; }
			public int Number { get; set; }
			public decimal Amount { get; set; }
			public DateTime CreatedTime { get; set; }
		}

		#endregion

		#region AjaxResult HeyueXiangqing(HeyueXiangqingParameter parameter)

		public AjaxResult HeyueXiangqing(HeyueXiangqingParameter parameter)
		{
			//订单详情
			var query = _unitOfWork.DbContext.Queryable<Model.DB.Business>()
				.Where(p => p.Id == parameter.Id)
				.Select(p => new HeyueXiangqingModel
				{
					Id = p.Id,
					ProductName = p.ProductName,
					Hashrate = p.Hashrate,
					HashrateString = p.Hashrate.ToString(),
					ElectricCharge = p.ElectricCharge,
					Price = p.Price,
					Number = p.Number,
					Amount = p.Amount,
					CreatedTime = p.CreatedTime
				});
			HeyueXiangqingModel entity = query.First() ?? new HeyueXiangqingModel();

			//总收益
			decimal shouyi = _unitOfWork.DbContext.Queryable<Model.DB.BusinessIncomeRunnings>()
				.Where(p => p.BusinessId == parameter.Id)
				.Sum(p => (decimal?)p.Amount).GetValueOrDefault();
			entity.TotalShouyi = shouyi;

			return new AjaxResult("Success", AjaxResultType.Success, entity);
		}

		public class HeyueXiangqingParameter
		{
			public int Id { get; set; }
		}

		public class HeyueXiangqingModel
		{
			public int Id { get; set; }
			public string ProductName { get; set; }
			public decimal Hashrate { get; set; }
			public string HashrateString { get; set; }
			public decimal ElectricCharge { get; set; }//单份日电费
			public decimal TotalElectricCharge { get { return ElectricCharge * Number; } }
			public decimal Price { get; set; }
			public int Number { get; set; }
			public decimal Amount { get; set; }
			public DateTime CreatedTime { get; set; }
			public decimal ShouyiOfDay { get; set; }//单份预计日收益
			public decimal TotalShouyiOfDay { get { return ShouyiOfDay * Number; } }
			public decimal TotalShouyi { get; set; }//总收益（已获收益）
		}

		#endregion

		#region AjaxResult Shouyi(ShouyiParameter parameter)

		public AjaxResult Shouyi(ShouyiParameter parameter)
		{
			//收益列表
			var query = _unitOfWork.DbContext.Queryable<Model.DB.BusinessIncomeRunnings>()
				.Where(p => p.BusinessId == parameter.Id)
				.Select(p => new ShouyiRowsModel
				{
					Id = p.Id,
					Amount = p.Amount,
					ElectricCharge = p.ElectricCharge,
					ElectricChargeBTC = p.ElectricChargeBTC,
					ElectricChargeBalance = p.ElectricChargeBalance,
					TotalAmount = p.Amount + p.ElectricChargeBTC,
					CreatedTime = p.CreatedTime
				});

			//汇总
			decimal totalElectricCharge = query.Sum(p => (decimal?)p.ElectricCharge).GetValueOrDefault();
			decimal totalElectricChargeBTC = query.Sum(p => (decimal?)p.ElectricChargeBTC).GetValueOrDefault();
			decimal totalNetEarning = query.Sum(p => (decimal?)p.Amount).GetValueOrDefault();
			decimal totalEarnings = totalNetEarning + totalElectricChargeBTC;
			decimal electricChargeBalance = new Service.DAL(_unitOfWork).UserElectricityBalance(LoginUserId);

			int total = 0;
			var list = query.ToPageList(parameter.Page, parameter.Limit, ref total);

			//订单信息
			var entityBusiness = _unitOfWork.DbContext.Queryable<Business>().Where(p => p.Id == parameter.Id).First();
			string productName = entityBusiness != null ? entityBusiness.ProductName : "";
			int productNumber = entityBusiness != null ? entityBusiness.Number : 0;
			string totalHashrate = entityBusiness != null ? Common.Utility.ConvertHashrate(entityBusiness.Hashrate * entityBusiness.Number) : "";

			//返回数据
			var result = new ShouyiModel
			{
				Rows = list,
				Total = total,
				ProductName = productName,
				ProductNumber = productNumber,
				TotalHashrate = totalHashrate,
				TotalElectricCharge = totalElectricCharge,
				TotalElectricChargeBTC = totalElectricChargeBTC,
				TotalNetEarning = totalNetEarning,
				TotalEarnings = totalEarnings,
				ElectricChargeBalance = electricChargeBalance
			};

			return new AjaxResult("Success", AjaxResultType.Success, result);
		}

		public class ShouyiParameter
		{
			public int Id { get; set; }
			public int Page { get; set; } = 1;
			public int Limit { get; set; } = 20;
		}

		public class ShouyiModel
		{
			public List<ShouyiRowsModel> Rows { get; set; } = new List<ShouyiRowsModel>();
			public int Total { get; set; }
			public string ProductName { get; set; }
			public int ProductNumber { get; set; }
			public string TotalHashrate { get; set; }
			public decimal TotalElectricCharge { get; set; }
			public decimal TotalElectricChargeBTC { get; set; }
			public decimal TotalNetEarning { get; set; }
			public decimal TotalEarnings { get; set; }
			public decimal ElectricChargeBalance { get; set; }
		}

		public class ShouyiRowsModel
		{
			public int Id { get; set; }
			
			/// <summary>
			/// 净收益
			/// </summary>
			public decimal Amount { get; set; }

			public decimal TotalAmount { get; set; }
			public decimal ElectricCharge { get; set; }
			public decimal ElectricChargeBTC { get; set; }
			public decimal ElectricChargeBalance { get; set; }
			public DateTime CreatedTime { get; set; }
		}

		#endregion

		#region AjaxResult DianfeiChongzhi()

		public AjaxResult DianfeiChongzhi()
		{
			decimal amount = new Service.DAL(_unitOfWork).UserElectricityBalance(LoginUserId);

			var result = new DianfeiChongzhiModel
			{
				Amount = amount
			};

			return new AjaxResult("Success", AjaxResultType.Success, result);
		}

		public class DianfeiChongzhiModel
		{
			public decimal Amount { get; set; }
		}

		#endregion

		#region AjaxResult DianfeiJilu(DianfeiJiluParameter parameter)

		public AjaxResult DianfeiJilu(DianfeiJiluParameter parameter)
		{
			var query = _unitOfWork.DbContext.Queryable<UserElectricity>()
				.Where(p => p.UserId == LoginUserId && p.Amount > 0)
				.Select(p => new DianfeiJiluRowsModel
				{
					Id = p.Id,
					Amount = p.Amount,
					CreatedTime = p.CreatedTime
				});

			decimal totalAmount = query.Sum(p => (decimal?)p.Amount).GetValueOrDefault();

			int total = 0;
			var list = query.ToPageList(parameter.Page, parameter.Limit, ref total);

			var result = new DianfeiJiluModel
			{
				Rows = list,
				Total = total,
				TotalAmount = totalAmount
			};

			return new AjaxResult("Success", AjaxResultType.Success, result);
		}

		public class DianfeiJiluParameter
		{
			public int Page { get; set; } = 1;
			public int Limit { get; set; } = 20;
		}

		public class DianfeiJiluModel
		{
			public List<DianfeiJiluRowsModel> Rows { get; set; }
			public int Total { get; set; }
			public decimal TotalAmount { get; set; }
		}

		public class DianfeiJiluRowsModel
		{
			public int Id { get; set; }
			public decimal Amount { get; set; }
			public DateTime CreatedTime { get; set; }
		}

		#endregion

		public AjaxResult Ceshi()
		{
			Service.Model.PoolCoinDetails entity = Service.FkPool.PoolCoinDetails();
			return new AjaxResult("", AjaxResultType.Success, entity);
		}

		#region AjaxResult MyReward()

		[HttpPost]
		public AjaxResult MyReward()
		{
			//我的客户
			List<int> afterUserIds = new Service.DAL(_unitOfWork).GetAfterUserIds(LoginUserId);
			afterUserIds.Insert(0, LoginUserId);



			//ProductListDto
			//int total = 0;
			//var data = _unitOfWork.DbContext.Queryable<Product>().Select(m => new
			//{
			//	BType = m.BType,
			//	ExpectYield = 0,
			//	Price = m.Price,
			//	Id = m.Id,
			//	ProductUnit = m.ProductUnit,
			//	Quantity = m.Quantity,
			//	Term = m.Term

			//}).ToPageList(pageIndex, pageSize, ref total);
			return new AjaxResult("允许访问", AjaxResultType.Success, new { Data = 0, Total = 0 });
		}

		public class MyRewardModel
		{
			
		}

		public class MyRewardKehuModel
		{
			public int Id { get; set; }
			public string UserName { get; set; }
			public string Phone { get; set; }
		}

		#endregion



		//#region List<int> GetAfterUserIds(int userId) 获取指定用户所有下级用户的Id集合。

		///// <summary>
		///// 获取指定用户所有下级用户的Id集合。
		///// </summary>
		///// <param name="userId"></param>
		///// <returns></returns>
		//private List<int> GetAfterUserIds(int userId)
		//{
		//	List<int> result = new List<int>();

		//	var query = _businessContract.UnitOfWork.DbContext.Queryable<Model.DB.Identity.Users, Model.DB.Identity.UserMap>(
		//		(a, b) => a.Id == b.UserId)
		//		.Where((a, b) => ((b.SuperId == userId
		//			|| b.SuperSalesmanId == userId
		//			|| b.InterfaceId == userId
		//			|| b.InterfaceSalesmanId == userId
		//			|| b.AgentId == userId
		//			|| b.AgentSalesmanId == userId))
		//			&& !a.IsDeleted)
		//		.Select((a, b) => a.Id);

		//	result = query.ToList();
		//	return result;
		//}

		//#endregion

		//#region List<int> GetAfterBusinessIds(int userId) 获取指定用户所有下级用户的订单。

		///// <summary>
		///// 获取指定用户所有下级用户的订单。
		///// </summary>
		///// <param name="userId">用户Id</param>
		///// <returns></returns>
		//private List<int> GetAfterBusinessIds(int userId)
		//{
		//	//用户角色表
		//	//1超级管理员 2公司业务 3接口商 4接口商下的业务员 5代理商 6代理商下的业务员 7用户

		//	List<int> result = new List<int>();

		//	int roleId = _usersContract.Entities.AsQueryable().Where(p => p.Id == userId).Select(p => p.RoleID).First();
		//	if (roleId <= 0)
		//		return result;

		//	var query = _businessContract.UnitOfWork.DbContext.Queryable<Model.DB.Business, Model.DB.Identity.UserMap>(
		//		(a, b) => a.UserId == b.UserId)
		//		.Where((a, b) => (roleId == 1 && b.SuperId == userId)
		//			|| (roleId == 2 && b.SuperSalesmanId == userId)
		//			|| (roleId == 3 && b.InterfaceId == userId)
		//			|| (roleId == 4 && b.InterfaceSalesmanId == userId)
		//			|| (roleId == 5 && b.AgentId == userId)
		//			|| (roleId == 6 && b.AgentSalesmanId == userId))
		//		.OrderBy((a, b) => a.CreatedTime)
		//		.Select((a, b) => a.Id);

		//	result = query.ToList();
		//	return result;
		//}

		//#endregion
	}
}
